var upOrDownImgPath = '../../staticFile/images/mobile/',
	imgPosition = '<img src="../../staticFile/images/mobile/position.png" class="img-position"> ', loadNum = 0,
currentCityName = '',lastCityName,currentCityCode = '',scsLat,scsLng,scsCurrentPage = 1, defaultPageSize = 10,soAreaCodes = '',soServiceTypeIds = '', bottomHeightRem = 3,isContinueLoad = true;
$(function(){
	var map, geolocation;
	//加载地图，调用浏览器定位服务
	map = new AMap.Map('aMapDiv', {
	    resizeEnable: true
	});
	var selectedCity = getSelectedCity();
	//如果没有选择城市
	if(selectedCity == null){
		//实例化城市查询类
		var citysearch = new AMap.CitySearch();
		//自动获取用户IP，返回当前城市
		citysearch.getLocalCity(function(status, result) {
		    if (status === 'complete' && result.info === 'OK') {
				citySearchComplete(result);
		    } else {
		    	setCurrentCity();
		    }
		    changeMyCityAndLoad();
		});
	}else{
		currentCityCode = selectedCity.selectCode;
		currentCityName = selectedCity.selectName;
		changeMyCityAndLoad();
		setLastCity();
	}
	
	$('.search-button').click(function() {
		scsCurrentPage = 1;
		$('#serviceList').children('.service-info').remove();
        isContinueLoad = true;
		listMIndexServiceOrderData(scsCurrentPage, defaultPageSize);
	});
	//浏览器定位
	AMap.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 30000,          //超过10秒后停止定位，默认：5s
            buttonPosition:'RB',    //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: false //true   //定位成功后是否自动调整地图视野到定位点
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function(status,result){
            if(status == 'complete'){
				onComplete(result);
            }else{
				onError(result);
            }
        });
    });
	
	$('#serviceType').click(function(){
        hiddenServiceArea();
        var displayValue = $('#selectServiceType').css('display');
        //如果是显示，就需要隐藏
        if (displayValue != 'none'){
            hiddenServiceType();
            return;
        }
        //如果数据没加载，则需要从后台再加载显示
        if($('#typeOption>.type-option').length <= 0){
        	listServiceType();
        }
        $('#serviceType>img').attr('src',upOrDownImgPath + 'up.png');
        $('#serviceType').css({'background-color':'white'});
        $('#selectServiceType').css({'display': 'inline-block'});
    });
    $('#serviceArea').click(function(){
        hiddenServiceType();
        var displayValue = $('#selectServiceArea').css('display');
        //如果不是隐藏，即显示，就隐藏
        if (displayValue != 'none'){
            hiddenServiceArea();
            return;
        }
        //如果数据没加载，则需要从后台再加载显示
        if($('#areaOption>.type-option').length <= 0){
            listAreaByCityCode();
        }
        $('#serviceArea>img').attr('src',upOrDownImgPath + 'up.png');
        $('#serviceArea').css({'background-color':'white'});
        $('#selectServiceArea').css({'display': 'inline-block'});
    });
    //服务类型重置
    $('#btnResetServiceType').click(function(){
    	soServiceTypeIds = '';
        $("input[name=cbServiceType]").removeAttr("checked");
    });
	//服务地区重置
    $('#btnResetArea').click(function(){
    	soAreaCodes = '';
        $("input[name=cbAreaType]").removeAttr("checked");
    });
    $('.btn-type-sure').click(function(){
		isContinueLoad = true;
        $('#serviceList').children('.service-info').remove();
        if (this.id == 'btnTypeSure'){
        	soServiceTypeIds = getCodeByTypeArea('typeOption');
            hiddenServiceType();//隐藏列表
        }else if (this.id == 'btnAreaSure'){
        	soAreaCodes = getCodeByTypeArea('areaOption');
            hiddenServiceArea();
        }
        scsCurrentPage = 1;
        listMIndexServiceOrderData(1, defaultPageSize);//请求主页页面数据
    });
    
    //监听滚动条事件
    $(window).scroll(function() {
    	var rem = parseFloat($('html').css('font-size').replace('px','')),
    	docScrollTop = $(document).scrollTop(), docHeight = $(document).height(), 
    	//loadHeight=1个rem单位所占像素 * 单个服务单高度 * 下拉到询问剩余rem个
    	winHeight = $(window).height(), loadHeight = rem * 3 * bottomHeightRem;
    	if ((docHeight - docScrollTop - winHeight) <= loadHeight) {
    		scsCurrentPage += 1;
    		listMIndexServiceOrderData(scsCurrentPage, defaultPageSize);
		}
	});
});
// 获取服务类型数据
function listServiceType(){
	var mServiceTypeList = getDictionaries('1');
	if (isNull(mServiceTypeList)) {
		return;
	}
	for (var g = 0; g < mServiceTypeList.length; g ++){
		var leftOrRight = (g + 1) % 2 == 0 ? 'right' : 'left', sta = mServiceTypeList[g];
		$('#typeOption').append(
		'<div class="' + leftOrRight + ' type-option"><span></span>' +
			'<input id="' + sta.id + '" name="cbServiceType" class="cb-option" type="checkbox" /><label>' + sta.dicName + '</label>' +
		'</div>');
	}
}
/**
 * 通过类型或区域编码获取选择的ID或code
 * @param taId
 */
function getCodeByTypeArea(taId) {
    var taList = '';
    $('#' + taId + ' .type-option input').each(function(){
        if($(this).prop('checked')) {
            taList += this.id + ',';
        }
    });
    if(taList.length > 1){
        taList = taList.substring(0, taList.length - 1);
    }
    return taList;
}
//获取区/县数据
function listAreaByCityCode(){
	$.ajax({
		type: 'post',
		url: '/app/index/listAreaByCityCode',
		dataType: 'json',
		async: false,
		timeout: 30000,
		data: {cityCode: currentCityCode},
		success: function(result) {
			if(result == null || result.length < 1){
	            return;
			}
			for (var g = 0; g < result.length; g ++){
				var leftOrRight = (g + 1) % 2 == 0 ? 'right' : 'left';
				$('#areaOption').append(
				'<div class="' + leftOrRight + ' type-option"><span></span>' +
					'<input id="' + result[g].areaCode + '" name="cbAreaType" class="cb-option" type="checkbox" /><label>' + result[g].areaName + '</label>' +
				'</div>');
			}
		}
	});
}
//定位失败的情况下，设置当前城市信息
function setCurrentCity(){
	lastCityName = localStorage.getItem(LAST_CITY_NAME_KEY);
	//如果上次保存的城市信息不存在，就将默认的城市信息赋值给当前城市
	if (lastCityName == null || lastCityName == '') {
		currentCityCode = defaultCityCode;
		defaultCityName = defaultCityName;
	}else {
		currentCityCode = localStorage.getItem(LAST_CITY_ID_KEY);
		currentCityName = localStorage.getItem(LAST_CITY_NAME_KEY);
	}
	setLastCity();
}

/**
 * 设置上次设置的城市
 */
function setLastCity() {
	var lastCityObj = {
		'code': currentCityCode,
		'name': currentCityName
	};
	localStorage.setItem(LAST_CITY, JSON.stringify(lastCityObj));
}
//解析定位结果
function onComplete(data) {
	scsLng = data.position.getLng(), scsLat = data.position.getLat();
	localStorage.setItem(LAST_LNG, scsLng);//经度
	localStorage.setItem(LAST_LAT, scsLat);//纬度
	sessionStorage.setItem(LAST_LNG, scsLng);
	sessionStorage.setItem(LAST_LAT, scsLat);
	//重新计算用户当前位置(高德地图基于浏览器定位)与订单服务地址的距离
	$(".order-lnglat").each(function(){
	    var lnglatArray = this.value.split('_');
	    var yourDistance = getDistanceByLatLng(scsLng,scsLat,Number(lnglatArray[1]),Number(lnglatArray[0]));
	    var billNoId = this.id.split('_')[1], disStr = (yourDistance / 1000).toFixed(2);
	    $('#distance_' + billNoId).html(imgPosition + disStr + ' 千米');
	    var aObj = I('a_' + billNoId);
		var aHref = aObj.href;
		aObj.href = aHref.split('&distance')[0] + '&distance=' + disStr;
	});
}
//解析定位错误信息
function onError(data) {
	getLat();
	getLng();
}
function getLat() {
	if (isNull(scsLat) || scsLat <= 0) {
		//从sessionStorage和localStorage中获取经纬度信息
		scsLat = sessionStorage.getItem(LAST_LAT);
		if (isNull(scsLat) || scsLat <= 0) {
			scsLat = localStorage.getItem(LAST_LAT);
		}
	}
	return scsLat;
}
function getLng() {
	if (isNull(scsLng) && scsLng <= 0) {
		//从sessionStorage和localStorage中获取经纬度信息
		scsLng = sessionStorage.getItem(LAST_LNG);
		if (isNull(scsLng) || scsLng <= 0) {
			scsLng = localStorage.getItem(LAST_LNG);
		}
	}
	return scsLng;
}
/**
 * 隐藏服务类型选择项
 */
function hiddenServiceType(){
    $('#selectServiceType').css({'display': 'none'});
    $('#serviceType>img').attr('src',upOrDownImgPath + 'down.png');
    $('#serviceType').css({'background-color':'#efefef'});
}
/**
 * 隐藏服务地区选择项
 */
function hiddenServiceArea(){
    $('#selectServiceArea').css({'display': 'none'});
    $('#serviceArea>img').attr('src',upOrDownImgPath + 'down.png');
    $('#serviceArea').css({'background-color':'#efefef'});
}
/**
 * 查询移动端订单数据
 * @param currentPage  当前页号
 * @param pageSize  每页显示行数
 * @returns
 */
function listMIndexServiceOrderData(currentPage, pageSize) {
	if(!isContinueLoad && (loadNum >= 1 || $('#loadInfo').is(':hidden'))){
		return;
	}
	$('#loadInfo').show();
	$.ajax({
		type: 'post',
		url: '/app/index/mIndexPageOrder',
		dataType: 'json',
		async: false,
		timeout: 30000,
		data: {
			cityCode: currentCityCode, 
			cityName: currentCityName,
			currentPage: currentPage,
			showCount: pageSize,
			soAreaCodes: soAreaCodes,
			soServiceTypeIds: soServiceTypeIds,
			soName: $('#searchServiceTitle').val()
		},
		success: function(mPage) {
			$('#loadInfo').hide();
			//加载次数自加1
			loadNum ++;
			var rem = parseFloat($('html').css('font-size').replace('px','')),
			//一个汉字所占宽度
			cnWordWidth = 0.6 * rem, adWordWidth = 0.5 * rem;
			//如果没有数据了，则不再加载
			if(!mPage.hasNextPage){
				isContinueLoad = false;
				$('#loadFinishInfo').show();
			}
			//服务订单数据
			var appendStr = '', titleWidth = getTitleWidth(rem);
			var titleNum = parseInt(titleWidth / cnWordWidth) - 1, addressNum = parseInt(titleWidth / adWordWidth) - 2;
			var mOrderList = mPage.list, mUserId = sessionStorage.getItem(SCS_USER_ID);
			if (isNull(mOrderList)){
				$('#loadInfo').before('很抱歉，没找到订单');
				return;
			}
			//经度,纬度
			var pLng = localStorage.getItem(LAST_LNG), pLat = localStorage.getItem(LAST_LAT);
			for (var s = 0; s < mOrderList.length; s ++) {
				var order = mOrderList[s];
				var provinceName = order.provinceName, cityName = order.cityName, soName = order.soName, soAmount = order.soAmount + '',
				address = order.soAddress;
				if (provinceName != cityName) {
					cityName = provinceName + cityName;
				}
				var yourDistance = '天涯海角', soBillNumber = order.soBillNumber, serviceDateStr = order.soServiceDate;
				serviceDateStr = serviceDateStr.substring(0, serviceDateStr.length - 3), oLat = order.soLat, oLng = order.soLng;
				if (!isNull(pLat) && !isNull(pLng) && Number(pLng) > 0 && Number(pLat) > 0) {
					yourDistance = getDistanceByLatLng(Number(pLng), Number(pLat), Number(oLng), Number(oLat));
					yourDistance = (yourDistance / 1000).toFixed(2);
				}

				if(soName.length > titleNum){
					soName = soName.substring(0,titleNum) + '...';
				}
				if(address.length > addressNum){
					address = address.substring(0,addressNum) + '...';
				}
				if(soAmount.indexOf('.') < 1){
					soAmount += '.0';
				}
				var btnRob = '', soUserId = order.soUserId;
				//如果登录人是发布人，则不能抢单
				if (mUserId == soUserId) {
					btnRob = '<button class="btn-grab-order" disabled="disabled">己单</button>';
				}else {
					btnRob = '<button onclick="robServiceOrder(\'' + soBillNumber + '\',this)" class="btn-grab-order can-grab">抢单</button>';
				}
				appendStr += getOrderHtml(soBillNumber, soUserId, yourDistance, soName, order, btnRob, address, serviceDateStr);
			}
			$('#loadInfo').before(appendStr);
		},
		error: function() {
			mTips('当前系统繁忙，请稍候再试');
			$('#loadInfo').hide();
		}
	});
}
/**
 * 获取服务订单标题宽度
 * @returns
 */
function getTitleWidth(rem){
	var bodyWidth = $("body").width();
	//标题左边距=service-info 左、右边距+service-info 左边距
	var titleLeft = (0.2 + 0.2 + 0.06) * rem;
	return (bodyWidth - titleLeft);
}
/**
 * 获取选择的城市
 */
function getSelectedCity(){
	var cityParam = decodeURI(decodeURI(location.search));
	if(cityParam.indexOf('?') < 0 || isNull(cityParam)){
		return null;
	}
	cityParam = cityParam.split('?')[1];
	var paramArray = cityParam.split('&');
	var paramObj = new Object();
	for(var g = 0; g < paramArray.length; g ++){
		var param = paramArray[g].split('=');
		paramObj[param[0]] = param[1];
	}
	return paramObj;
}
/**
 * 修改MyCity标签内容并加载数据
 * @returns
 */
function changeMyCityAndLoad(){
	var myCity = $('#myCity');
	myCity.text(currentCityName);
	var myCityProperties = {
		"href": 'mCityList.html?cityCode=' + currentCityCode,
		"name": currentCityCode
	};
	myCity.attr(myCityProperties);
	var len = currentCityName.length;
	myCity.css({'background-position': (len * 0.6) + 'rem -0.6rem','width': (len + 1) * 0.6 + 'rem'});
    listMIndexServiceOrderData(1, defaultPageSize);//请求主页页面数据
}
/**
 * 抢单
 * @param billNumber
 * @returns
 */
function robServiceOrder(billNumber,btnRoObj){
	var roObj = $(btnRoObj);
	if(!roObj.hasClass('can-grab')){
		return;
	}
	roObj.attr('disabled', true);//设置不可用
	roObj.removeClass('can-grab');
	//不能抢自己发布的订单
	var mUserId = sessionStorage.getItem(SCS_USER_ID), mUserName = sessionStorage.getItem(SCS_USER_NAME);
	//如果没有登录
	if(isNull(mUserId) || isNull(mUserName)){
		popTipShow.confirm('登录确认','您需要先登录才能抢单',['去登录','不去'],function(e){
			if($(e.target).attr('class') != 'ok'){
				this.hide();
                setCanRob(roObj);
				return;
			}
			window.location.href = '/userPages/mobile/mUserLogin.html';
		});
		return;
	}
	popTipShow.confirm('抢单确认','您确定要抢此单吗？',['确 定','取 消'],function(e){
		this.hide();
		if($(e.target).attr('class') != 'ok'){
			this.hide();
			roObj.attr('disabled', false);
			roObj.addClass('can-grab');
			return;
		}
		if (isNull(billNumber)) {
			mTips("抢单失败，请刷新后再试");
			return;
		}
		if(mUserId == $('#issuerUserId_' + billNumber).val()){
			mTips("您不能抢自己发布的订单");
			return;
		}
		webTips('<span>正在抢单中<img src="../../staticFile/images/index/loading.gif" style="width: 1rem;height: 1rem;"></span>',-1);
		$.ajax({
			type : "POST",
			url : '/serviceOrder/robServiceOrder',
			data : {
				userName : mUserName,
                billNumber : billNumber
			},
			dataType : 'json',
			cache : false,
			async: false,
			success : function(result) {
				var s = result.errorFlag;
				if ("0" == s && result.success) {
					mTips('恭喜，抢单成功!');
					$('#si_' + billNumber).remove();
				} else {
					mTips('抢单失败');
                    setCanRob(roObj);
				}
				$(".web_toast").fadeOut();
			},
			error: function() {
				$(".web_toast").fadeOut();
				mTips('抢单失败');
                setCanRob(roObj);
			}
		});
	});
}
function setCanRob(roBtn) {
    roBtn.attr('disabled', false);
    roBtn.addClass('can-grab');
}

/**
 * 根据IP定位城市成功
 * @param result
 */
function citySearchComplete(result) {
	if (!(result && result.city && result.bounds)) {
		return;
	}
	currentCityName = result.city;
	var lastOneLen = currentCityName.length - 1;
	if (currentCityName.substr(lastOneLen) == '市') {
		currentCityName = currentCityName.substr(0, lastOneLen);
	}
	//将上一次的城市名跟当前城市名相比较获取城市编号
	lastCityName = localStorage.getItem(LAST_CITY_NAME_KEY);
	if (lastCityName == currentCityName) {
		currentCityCode = localStorage.getItem(LAST_CITY_ID_KEY);
	} else {
		localStorage.setItem(LAST_CITY_ID_KEY, '');
		localStorage.setItem(LAST_CITY_NAME_KEY, currentCityName);
		currentCityCode = getCityIdByName('/', currentCityName);
	}
}

/**
 * 获取订单html
 * @returns {string}
 */
function getOrderHtml(soBillNumber, soUserId, yourDistance, soName, order, btnRob, address, serviceDateStr) {
	if (yourDistance != '天涯海角') {
		yourDistance += ' 千米';
	}
	return '<div class="service-info" id="si_' + soBillNumber + '">' +
		'<input type="hidden" id="issuerUserId_' + soBillNumber + '" value="' + soUserId + '">' +
		'<input type="hidden" id="order_' + soBillNumber + '" class="order-lnglat" value="' + oLat + '_' + oLng + '">' +
		'<ul>' +
		'<li class="service-title">' +
		'<a id="a_' + soBillNumber + '" href="/userPages/mobile/mOrderDetail.html?oid=' + order.soId + '&distance=' + yourDistance + '">' + soName + '</a>' +
		'</li>' +
		'<li class="ellipses">' + address + '</li>' +
		'<li>' + serviceDateStr + '&emsp;&emsp;' + order.serviceTypeName + '</li>' +
		'<li class="distance-money">' +
		'<div>￥' + order.soAmount + '</div>' +
		'<div id="distance_' + soBillNumber + '">' + imgPosition + yourDistance + '</div>' +
		'</li>' +
		'</ul>' +
		'<span class="grab-order">' + btnRob + '</span>' +
		'</div>';
}